package handler

import (
	"fmt"
	"git.oschina.net/cnjack/go-task/task"
	"net/http"
	"strconv"
	"time"
)

func IndexHandler(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	fmt.Fprintf(w, "Hello Go-Task!<br><a href=\"/tasklist\">view the task</a>")
}
func TaskListHandler(w http.ResponseWriter, req *http.Request) {
	var body string
	body = "当前列表:<br>"
	for _, task := range task.TaskList {
		body = body + "任务ID:" + strconv.Itoa(task.Id) + "|任务类型:" + task.TaskVaule + "|时间间隔:" + strconv.Itoa(int(task.Time)) + "|距离下次审核时间:" + strconv.Itoa(int(task.NextRunTime-time.Now().Unix())) + "<br/>"
	}
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	w.Write([]byte(body))
}

//http://127.0.0.1:3000/addtask?timev=3&taskType=1&taskVaule=127.0.0.1
func AddTaskHandler(w http.ResponseWriter, req *http.Request) {
	var timevint, _ = strconv.Atoi(req.FormValue("timev"))
	var timev = int64(timevint)
	var taskType, _ = strconv.Atoi(req.FormValue("taskType"))
	var taskVaule = "http://" + req.FormValue("taskVaule")
	task.Add(timev, taskType, taskVaule)
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	w.Write([]byte("添加成功"))
}
func DelTaskHandler(w http.ResponseWriter, req *http.Request) {
	var id, _ = strconv.Atoi(req.FormValue("id"))
	resp := task.Del(id)
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	if resp {
		w.Write([]byte("删除成功"))
	} else {
		w.Write([]byte("id不存在"))
	}
}
